package jccr;

public class ReceiveCoordinator extends CoordinatorBase {

	public ReceiveCoordinator( DispatcherQueue queue, RawPort port, boolean persistent ) {
		super(queue, persistent);
		
		if( port == null )
			throw new IllegalArgumentException();
						
		_port = coordinate(port);
		beginActivate();
	}
	
	@Override
	protected Iterable<Task> safeCoordinate( Object source ) {
		
		RawPort port = null;
		Object argument = null;
		
		/* since any coordination will render a port to be executed,
		 * (at least if a argument is available) start by grabbing the next
		 * argument from the port. If no port is available then no argument
		 * can be available.
		 */
		argument = _port != null ? _port.dequeueRaw() : null;			 
		if ( argument == null )
			return null;
		
		port = _port;
		
		/* finally we are ready to pass the message to the port.
		 */
		execute( port, argument );
		
		return null;
	}
	
	RawPort disconnectPort() {
		
		RawPort port = _port;
		_port = null;
		port.setCoordinator(null);
		return port;
	}
			
	RawPort _port;
}
